package com.dropdb.demo.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes({String[].class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class String2StringArrayTypeHandler extends BaseTypeHandler<String[]> {
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String[] strings, JdbcType jdbcType) throws SQLException {
        String string = null;
        try {
            string = objectMapper.writeValueAsString(strings);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        preparedStatement.setString(i, string);
    }

    @Override
    public String[] getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return this.getStringArray(resultSet.getString(s));
    }

    @Override
    public String[] getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return this.getStringArray(resultSet.getString(i));
    }

    @Override
    public String[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return this.getStringArray(callableStatement.getString(i));
    }

    private String[] getStringArray(String columnValue) {
        if (columnValue == null)
            return null;
        String[] strings = new String[0];
        try {
            strings = objectMapper.readValue(columnValue, String[].class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return strings;
    }
}
